package client.presenter;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import common.DataTransfer;

/**
 * 
 *
 */
public class ServerHandler {
	public static String serverIP;
	public static int connectionPort = -1;
	public static int socketTimeout = -1;
	
	/**
	 * Verifies that the settings were initialized correctly
	 * @throws IOException
	 */
	private static void verifySettings() throws IOException {
		if (serverIP == null || serverIP.isEmpty() ||
			connectionPort == -1 || socketTimeout == -1 ) {
			throw new IOException("Wrong connection settings.");
		}
	}
	
	/**
	 * Uses get hint method to read from client and send to server
	 * @param gameName the name of the current game
	 * @param board current state of the board
	 * @param score current score of the game
	 * @return hint for the next move
	 * @throws Exception
	 */
	public static int getHint(String gameName, int[][] board, int score) throws Exception {
		return getSolution(gameName, board, score).get(0);
	}
	
	/**
	 * Opens connection to server and sends the needed data
	 * @param gameName the name of the current game
	 * @param board current state of the board
	 * @param score current score of the game
	 * @return hint for the next move
	 * @throws UnknownHostException
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	@SuppressWarnings("unchecked")
	public static ArrayList<Integer> getSolution(String gameName, int[][] board, int score) throws UnknownHostException, IOException, ClassNotFoundException  {
		verifySettings();
		
		Socket connection = new Socket(InetAddress.getByName(serverIP), connectionPort);
		connection.setSoTimeout(socketTimeout);
		
		ObjectOutputStream  writer = new ObjectOutputStream(connection.getOutputStream());
		writer.writeObject(new DataTransfer(gameName, board, score));
		
		ObjectInputStream reader = new ObjectInputStream(connection.getInputStream());
		ArrayList<Integer> reuslt = (ArrayList<Integer>)reader.readObject();
		
		writer.close();
		reader.close();
		connection.close();

		return reuslt;
	}
}
